package com.snap.vseries.logger;

import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.LogStrategy;
import com.snap.vseries.AppConfig;
import com.snap.vseries.BuildConfig;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import static com.snap.vseries.logger.Utils.checkNotNull;

public class UserCsvFormatStrategy implements FormatStrategy {

    private static final String NEW_LINE = System.getProperty("line.separator");
    private static final String SEPARATOR = ",";

    @NonNull
    private final Date date;
    @NonNull
    private final SimpleDateFormat dateFormat;
    @NonNull
    private final LogStrategy logStrategy;

    UserCsvFormatStrategy() {
        date = new Date();
        dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS", Locale.CHINA);

        String folder = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separatorChar + AppConfig.LOG_DIRECTORY;
        HandlerThread ht = new HandlerThread("AndroidFileLogger." + folder);
        ht.start();
        Handler handler = new UserLogStrategy.WriteHandler(ht.getLooper(), folder);
        logStrategy = new UserLogStrategy(handler);
    }

    @Override
    public void log(int priority, @Nullable String onceOnlyTag, @NonNull String message) {
        checkNotNull(message);

        StringBuilder builder = new StringBuilder();

        // human-readable date/time
        date.setTime(System.currentTimeMillis());
        builder.append(dateFormat.format(date));

        // machine-readable date/time
        builder.append(SEPARATOR);
        builder.append(date.getTime());

        // level
        builder.append(SEPARATOR);
        builder.append(Utils.logLevel(priority));
        if (onceOnlyTag != null) {
            builder.append("-");
            builder.append(onceOnlyTag);
        }

        builder.append(SEPARATOR);
        builder.append(BuildConfig.VERSION_NAME);

        builder.append(SEPARATOR);
        builder.append(message);

        // new line
        builder.append(NEW_LINE);

        logStrategy.log(priority, onceOnlyTag, builder.toString());
    }
}